package com.linxin.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linxin.reggie.common.Result;
import com.linxin.reggie.dto.DishDto;
import com.linxin.reggie.dto.SetmealDto;
import com.linxin.reggie.entity.Category;
import com.linxin.reggie.entity.Dish;
import com.linxin.reggie.entity.Setmeal;
import com.linxin.reggie.entity.SetmealDish;
import com.linxin.reggie.service.CategoryService;
import com.linxin.reggie.service.DishService;
import com.linxin.reggie.service.SetmealDishService;
import com.linxin.reggie.service.SetmealService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.compiler.ast.Stmnt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetmealController {
    // 操作两张表
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping()
    // 添加新套餐时需要清除缓存
    // allEntries = true 这类缓存下的所有缓存
    @CacheEvict(value = "setmealCache", allEntries = true)
    @ApiOperation(value = "添加套餐")
    @ApiImplicitParams(
            // name: 参数名
            // value: 需要设置的名字
            // required: 是否必须
            @ApiImplicitParam(name = "setmealDto", value = "套餐Dto",required = true)
    )
    public Result<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("新增套餐的信息为: {}", setmealDto);

        // 在setmealService新增方法
        setmealService.saveWithDish(setmealDto);

        return Result.success("添加成功!!!");
    }

    /**
     * 套餐管理分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name) {
        // 分页构造器
        Page<Setmeal> setmealPageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPageInfo = new Page<>(page, pageSize);

        // 查询条件
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 模糊查询
        setmealLambdaQueryWrapper.like(name != null, Setmeal::getName, name);
        // 排序条件
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        // 查询
        setmealService.page(setmealPageInfo, setmealLambdaQueryWrapper);

        // 拷贝对象(records不用拷贝, 需要重新设置)
        BeanUtils.copyProperties(setmealPageInfo, setmealDtoPageInfo, "records");

        // 设置records
        // 获取setmealPageInfo的records
        List<Setmeal> records = setmealPageInfo.getRecords();
        // 流处理
        List<SetmealDto> setmealDtoList = records.stream().map((item) -> {
            // 拷贝对象
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            // 获取分类id
            Long categoryId = item.getCategoryId();
            // 根据id查询分类信息
            Category category = categoryService.getById(categoryId);
            // 设置分类名称
            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPageInfo.setRecords(setmealDtoList);

        return Result.success(setmealDtoPageInfo);
    }

    /**
     * 删除套餐(批量删除)
     *
     * @param ids
     * @return
     * @RequestParam注解 接收url?后面的数据
     */
    @DeleteMapping
    // 删除时需要清除缓存
    // allEntries = true 这类缓存下的所有缓存
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> delete(@RequestParam List<Long> ids) {
        log.info("需要删除的id为: {}", ids);
        // 在setmealService新增删除方法
        setmealService.removeWithDish(ids);

        return Result.success("删除成功!!!");
    }

    /**
     * 套餐启售和停售
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> setStatus(@PathVariable int status, @RequestParam List<Long> ids) {
        log.info("接收的status为: {}, ids为: {}", status, ids);
        // 获取这些id的数据
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 范围查询
        setmealLambdaQueryWrapper.in(Setmeal::getId, ids);
        // 获取这些数据
        List<Setmeal> list = setmealService.list(setmealLambdaQueryWrapper);

        // 设置list的状态
        list = list.stream().map((item) -> {
            // 设置他们的状态
            item.setStatus(status);
            return item;
        }).collect(Collectors.toList());

        setmealService.updateBatchById(list);

        // 返回结果
        if (status == 1) {
            return Result.success("套餐启售成功!!!");
        } else {
            return Result.success("套餐启售失败!!!");
        }
    }

    /**
     * 修改套餐用于页面回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<SetmealDto> getSetmealDto(@PathVariable Long id) {
        log.info("查询的id为: {}", id);

        // 根据id查询setmeal表中的基本信息
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        // 对象拷贝
        BeanUtils.copyProperties(setmeal, setmealDto);
        // 查询关联表setmeal_dish的菜品信息
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
        //设置套餐菜品属性
        setmealDto.setSetmealDishes(setmealDishList);

        return Result.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping// put请求参数必须加@RequestBody
    public Result<String> update(@RequestBody SetmealDto setmealDto) {
        log.info("需要修改的套餐为: {}", setmealDto);

        // 在setmealService扩展update方法
        setmealService.updateWithDish(setmealDto);

        return Result.success("修改成功!!!");
    }

    /**
     * 移动端页面套餐展示(分类id, 状态)
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    // @Cacheable(value = "缓存名称",key = "key名字")
    // key = "", #传入的参数.对应对象的属性, 需要拼接则添加'拼接的内容'
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public Result<List<Setmeal>> list(Setmeal setmeal) {
        log.info("分类id: {}, 状态为: {}", setmeal.getCategoryId(), setmeal.getStatus());

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 等值查询, 分类id
        setmealLambdaQueryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        // 等值查询, 状态为1
        setmealLambdaQueryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);

        return Result.success(setmealList);
    }

    @GetMapping("/dish/{setmealId}")
    public Result<List<DishDto>> listDish(@PathVariable Long setmealId) {
        log.info("接收的id为: {}", setmealId);

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealId);
        //获取套餐里面的所有菜品  这个就是SetmealDish表里面的数据
        List<SetmealDish> list = setmealDishService.list(queryWrapper);

        List<DishDto> dishDtos = list.stream().map((setmealDish) -> {
            DishDto dishDto = new DishDto();
            //将套餐菜品关系表中的数据拷贝到dishDto中
            BeanUtils.copyProperties(setmealDish, dishDto);
            //这里是为了把套餐中的菜品的基本信息填充到dto中，比如菜品描述，菜品图片等菜品的基本信息
            Long dishId = setmealDish.getDishId();
            Dish dish = dishService.getById(dishId);
            //将菜品信息拷贝到dishDto中
            BeanUtils.copyProperties(dish, dishDto);

            return dishDto;
        }).collect(Collectors.toList());

        return Result.success(dishDtos);
    }
}
